package cn.bigcontainer.alt.meta.controller;

import java.io.File;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import cn.bigcontainer.alt.common.exception.BigResultCode;
import cn.bigcontainer.alt.common.util.BigConstant;
import cn.bigcontainer.alt.meta.dto.MFileDto;
import cn.bigcontainer.alt.meta.service.MFileService;

@Controller
@RequestMapping("/meta/file")
@SessionAttributes(BigConstant.SESSION_USER)
public class MFileController {

	@Resource
	private MFileService fileService;

	@PostMapping
	@ResponseBody
	public BigResultCode upload(MultipartFile file, @RequestParam Map<String, Object> req, Map<String, Object> map) {
		MFileDto f = fileService.upload(file, req);
		return BigResultCode.getSuccessCode().setContent(f);
	}

	@GetMapping("/{id}")
	public ResponseEntity<FileSystemResource> download(@PathVariable("id") Integer id) {
		File f = fileService.getFile(id);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
		headers.add("Content-Disposition", "attachment; filename=" + f.getName());
		headers.add("Pragma", "no-cache");
		headers.add("Expires", "0");
		headers.add("Last-Modified", new Date().toString());
		headers.add("ETag", String.valueOf(System.currentTimeMillis()));
		return ResponseEntity.ok().headers(headers).contentLength(f.length())
				.contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(f));
	}

	@PostMapping("/json/{id}")
	@ResponseBody
	public BigResultCode getJson(@PathVariable("id") Integer id) {
		MFileDto f = fileService.getById(id);
		return BigResultCode.getSuccessCode().setContent(f);
	}
}
